package sk.fiit.vppj.eventmanager.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Class, which handles configuration(loaded from included property file or config.xml) of our application
 * @author Marek
 */
public final class ConfigManager {

	// application property field
	private Properties appConfig = null;
	private final static Logger log = Logger.getLogger( ConfigManager.class.getName() );
	// default configuration file name
	String configFile = "config.xml";

	public ConfigManager() {
		initiate();
	}

	/**
	 * Initialization method which load necessary configuration from packed config file. In case, config.xml is found, class takes
	 * configuration properties from that file
	 */
	private void initiate() {
		try {
			Properties defaultConfig = new Properties();
			// load default property file
			InputStream in = this.getClass().getResourceAsStream( "/resources/em.properties" );

			defaultConfig.load( in );
			in.close(); // close stream

			appConfig = new Properties( defaultConfig );
			boolean exists = new File( this.configFile ).exists(); //checks whether config.xml exists
			if( exists ) {
				in = new FileInputStream( new File( this.configFile ) );
				appConfig.loadFromXML( in );
				in.close();
			}
		}
		catch ( InvalidPropertiesFormatException e ) {
			log.log( Level.SEVERE, "Property file is invalid!", e );
			e.printStackTrace();
		}
		catch ( IOException e ) {
			log.log( Level.SEVERE, "Property file can't be read!", e );
			e.printStackTrace();
		}

	}

	public Properties getProperties() {
		return this.appConfig;
	}

	/**
	 * Method set properties into config.xml file
	 * @param key property name
	 * @param value value of property to set
	 */
	public void setProperty(String key, String value) {
		FileOutputStream out;
		try {
			out = new FileOutputStream( new File( this.configFile ) );
			this.appConfig.put( key, value );
			this.appConfig.storeToXML( out, null, "UTF-8" );
			out.close();
		}
		catch ( FileNotFoundException e ) {
			log.log( Level.WARNING, "XML Property file doesn't exist!", e );
			e.printStackTrace();
		}
		catch ( IOException e ) {
			log.log( Level.WARNING, "XML Property file can't be stored!", e );
			e.printStackTrace();
		}

	}

}
